import { h, ref, watch } from 'vue';

import { message, Modal } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  checkUploaded,
  createAiProcess,
  getAiProcessStatus,
  uploadImage,
} from '#/api';
import { calculateFileMD5, urlToBlob } from '#/utils';

import CheckUi from './copm/checkUi.vue';

export const addAiImageStore = defineStore('addAiImage', () => {
  const showAddAiImageBox = ref(false);
  const selectImageList = ref<any[]>([]);
  const lodingFromMaxAi = ref(false);
  const nowSelectUseAiItem = ref<any>({});

  const allAiList = ref<any[]>([]);

  function $reset() {
    showAddAiImageBox.value = false;
    selectImageList.value = [];
    lodingFromMaxAi.value = false;
    nowSelectUseAiItem.value = {};
    allAiList.value = [];
  }
  let getAiImageCb = (_agur: any) => {};
  watch(showAddAiImageBox, () => {
    if (!showAddAiImageBox.value) {
      $reset();
    }
  });
  function openAddAiImageBox(list: any, cb: any) {
    // console.log(list);
    if (!list || list.length === 0) return message.error('请选择图片');
    showAddAiImageBox.value = true;
    selectImageList.value = list.map((i: any, index: number) => {
      i.checked = false;
      i.lodingStatus = false;
      i.upImage = '';
      i.aiImageList = [];
      i.proceid = '';
      i.replaenum = 0;
      i.replaMaxnum = 20;
      i.errText = '';

      if (index === 0) {
        i.checked = true;
        nowSelectUseAiItem.value = i;
      }
      return i;
    });
    // console.log(selectImageList.value);
    getAiImageCb = cb;

    lodingFromMaxAi.value = true;

    setTimeout(() => {
      lodingFromMaxAi.value = false;
    }, 1000);
  }
  function putSelectImageList() {
    // 提示用户所选的图片
    Modal.confirm({
      title: '提示',
      content: h(CheckUi, {}, () => 'content'),
      okText: '确定',
      cancelText: '取消',
      width: 600,
      zIndex: 1002,
      onOk: () => {
        getAiImageCb(selectImageList.value);
        showAddAiImageBox.value = false;
      },
    });
  }
  function selectImage(item: any) {
    selectImageList.value = selectImageList.value.map((i: any) => {
      i.checked = false;
      return i;
    });
    nowSelectUseAiItem.value = item;
    item.checked = true;
  }

  async function cretedUseAiItem(list: any) {
    lodingFromMaxAi.value = true;
    list.forEach((item: any) => {
      item.lodingStatus = true;
      item.replaenum = 0;
      item.errText = '';
    });
    const getBlobList = await Promise.all(
      list.map((i: any) => urlToBlob(i.oldUrl)),
    );
    const getBlobListMd5: any = await Promise.all(
      getBlobList.map((i: any) => calculateFileMD5(i)),
    );
    // console.log('getBlobList', getBlobList, getBlobListMd5);

    const checkList = await Promise.all(
      getBlobListMd5.map(async (i: any, index: number) => {
        const reouer = await checkUploaded({ md5: i }).catch(() => {
          list[index].lodingStatus = false;
          list[index].errText = '本次AI生成失败，请重试';
          lodingFromMaxAi.value = false;
          return false;
        });
        return reouer;
      }),
    );
    const loderImageAll: any = [];

    checkList.forEach((i: any, index: number) => {
      if (!i) return;
      if (JSON.stringify(i) === '{}') {
        const newFromData = new FormData();
        newFromData.append('image', getBlobList[index]);
        newFromData.append('md5', getBlobListMd5[index]);
        loderImageAll.push(uploadImageFn(newFromData, list[index]));
      } else {
        list[index].upImage = i.url;
        list[index]._id = i._id;
        loderImageAll.push(startGetAiImage(list[index]));
      }
    });
    Promise.all(loderImageAll).then((_res: any) => {
      // console.log('所有的上传结果', res);
      lodingFromMaxAi.value = false;
    });
  }

  // 上传图片
  async function uploadImageFn(data: any, item: any) {
    const res: any = await uploadImage(data).catch(() => {
      item.lodingStatus = false;
      item.errText = '本次AI生成失败，请重试';
      lodingFromMaxAi.value = false;
      return false;
    });
    item.upImage = res.url;
    item._id = res._id;
    if (!res) {
      item.lodingStatus = false;
      item.errText = '本次AI生成失败，请重试';
      lodingFromMaxAi.value = false;
      return;
    }

    return startGetAiImage(item);
  }
  // 这里开始创作AI
  async function startGetAiImage(item: any) {
    const res = await createAiProcess({ img: item._id }).catch(() => {
      item.lodingStatus = false;
      item.errText = '本次AI生成失败，请重试';
      lodingFromMaxAi.value = false;
      return false;
    });
    if (!res) {
      item.lodingStatus = false;
      item.errText = '本次AI生成失败，请重试';
      lodingFromMaxAi.value = false;
      return;
    }
    item.proceid = res;
    return getAiImageResult(item);
  }

  // 轮训获取AI的结果
  function getAiImageResult(item: any, resro?: any) {
    lodingFromMaxAi.value = true;
    item.lodingStatus = true;
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      resro = resro || resolve;
      const res = await getAiProcessStatus({ id: item.proceid }).catch(() => {
        item.lodingStatus = false;
        item.errText = '本次AI生成失败，请重试';
        lodingFromMaxAi.value = false;
        return false;
      });
      if (!res) return;

      if (res.origin_url) {
        item.lodingStatus = false;
        item.aiImageList.push(
          ...res.target_list.map((i: any) => {
            const renderImage = {
              url: i,
              useStatus: false,
            };
            return renderImage;
          }),
        );
        allAiList.value.push(...item.aiImageList);
        resro(item);
      } else {
        item.replaenum++;
        if (item.replaenum > item.replaMaxnum) {
          item.lodingStatus = false;
          item.errText = '本次AI生成失败，请重试';
          resro(item);
          return;
        }
        setTimeout(() => {
          getAiImageResult(item, resro);
        }, 1500);
      }
    });
  }

  // 选择当前的图片到这里
  function selectNowImage(image: any) {
    nowSelectUseAiItem.value.newUrl = image.url;
  }

  return {
    $reset,
    showAddAiImageBox,
    openAddAiImageBox,
    getAiImageCb,
    putSelectImageList,
    lodingFromMaxAi,
    selectImageList,
    selectImage,
    nowSelectUseAiItem,
    cretedUseAiItem,
    allAiList,
    selectNowImage,
  };
});
